import { Component, Input, OnInit, Output, EventEmitter, AfterViewInit, ElementRef, ViewChild, AfterContentInit } from '@angular/core';

declare namespace CodeMirror {
  function fromTextArea(e: any, options?: any): any;
}

@Component({
  selector: 'codemirror-editor',
  templateUrl: './codemirror-editor.component.html',
  styleUrls: ['./codemirror-editor.component.scss']
})
export class CodemirrorEditorComponent implements OnInit, AfterViewInit, AfterContentInit {

  constructor() { }

  @ViewChild('tref', { read: ElementRef }) tref!: ElementRef;
  @Input() lang:string = "markdown";
  @Input() lineNumbers:boolean = false;

  @Input() value!:string;
  @Output() valueChange = new EventEmitter<string>();

  ngOnInit(): void {

  }
  ngAfterContentInit(): void {

   

  }
  ngAfterViewInit(): void {
    let editor = CodeMirror.fromTextArea(this.tref.nativeElement, {
      mode: this.lang,
      lineNumbers: this.lineNumbers,
      theme: 'default',
      lineWrapping: true,
      extraKeys: { Enter: 'newlineAndIndentContinueMarkdownList' },
      matchBrackets: true,      
      autoRefresh: true
    });
    editor.on('change', (e: any, o: any) => this.changeValue(e, this));
    editor.setSize('auto', '100%');
    setTimeout(() => {
      editor.refresh();
    }, 1000);
  }
  private changeValue(e: any, that: any) {
    let v = e.getValue();
    that.value = v;
    that.valueChange.emit(v);
  }
}
